from django.conf import settings
import os, uuid, json, time
from django.shortcuts import HttpResponse
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.decorators import login_required



def write_disk(file_obj, dir_path):
    '''上传文件写入到硬盘'''
    file_suffix = file_obj.name.split('.')[-1]
    if file_suffix.lower() not in settings.ALLOW_SUFFIX:
        return {'status': False}

    file_name = str(uuid.uuid1()) + '.' + file_obj.name.split('.')[-1]
    file_dir = os.path.join(settings.MEDIA_ROOT, dir_path)
    #文件夹没有创建文件夹
    if not os.path.exists(file_dir):
        os.makedirs(file_dir)
    dir_name = time.strftime('%Y%m%d')
    month_dir = os.path.join(file_dir, dir_name)
    if not os.path.exists(month_dir):
        os.makedirs(month_dir)
    file_path = os.path.join(month_dir, file_name)
    #写入硬盘
    try:
        with open(file_path, 'wb') as f:
            for chunk in file_obj.chunks():
                f.write(chunk)
        return {
            'status': True,
            'url': '%s%s/%s/%s' % (settings.MEDIA_URL, dir_path, dir_name, file_name),
            'filename': file_name
        }
    except:
        return {
            'status': False,
        }

@csrf_exempt
def upload_file(request):
    if request.method == "GET":
        res = {
            'state': 'SUCCESS',
            'url': '%s%s/%s/%s' % (settings.MEDIA_URL, 'images', time.strftime('%Y%m%d'), ''),
            'originalName': '',
            'name': '',
            'size': 0,
            'type': '.jpg'
        }
        f = open(os.path.join(os.path.join(os.path.join(os.path.join(settings.BASE_DIR, 'static'), 'xadmin'), 'ueditor'), 'config.json'), 'r')
        res = json.loads(f.read())
        f.close()
        return JsonResponse(res)
    else:
        #上传附件和多图上传
        if request.GET.get('action') == 'uploadfile' or request.GET.get('action') == 'uploadimage':
            file_obj = request.FILES.get('upfile')
            dir_path = 'files'
            result = write_disk(file_obj, dir_path)

            if result['status']:
                res = {
                    "state": "SUCCESS",
                    "url": result['url'],
                    "title": result['filename'],
                    "original": result['filename']
                }
            else:
                res = {
                    "state": "上传失败",
                    #"url": result['url'],
                    #"title": result['filename'],
                    #"original": result['filename']
                }
            return JsonResponse(res)

        #单图上传和单视频上传
        else:
            callback = request.GET.get('callback')
            editorid = request.GET.get('editorid')
            file_name = ''
            dir_path = ''
            file_obj = ''
            try:
                if request.FILES.get('file'):
                    dir_path = 'video'
                    file_obj = request.FILES['file']
                else:
                    dir_path = 'images'
                    file_obj = file_obj = request.FILES['undefined']  #ueditor单文件上传名字就是undefined


                file_suffix = file_obj.name.split('.')[-1]

                if file_suffix not in settings.ALLOW_SUFFIX:
                    return JsonResponse({'error': 1, 'message': '文件不被允许'})

                file_name = str(uuid.uuid1()) + '.' + file_obj.name.split('.')[-1]
                file_dir = os.path.join(settings.MEDIA_ROOT, dir_path)
                if not os.path.exists(file_dir):
                    os.makedirs(file_dir)
                month_dir = os.path.join(file_dir, time.strftime('%Y%m%d'))
                if not os.path.exists(month_dir):
                    os.makedirs(month_dir)
                file_path = os.path.join(month_dir, file_name)


                with open(file_path, 'wb') as f:
                    for chunk in file_obj.chunks():
                        f.write(chunk)
                res = {
                    'state': 'SUCCESS',
                    'url': '%s%s/%s/%s' % (settings.MEDIA_URL, dir_path, time.strftime('%Y%m%d'), file_name),
                    'originalName': file_name,
                    'name': file_name,
                    'size': file_obj.size,
                    'type': '.%s' % file_suffix
                }
                return JsonResponse(res)
            except Exception as e:
                res = {
                    'url': '%s%s/%s/%s' % (settings.MEDIA_URL, dir_path, time.strftime('%Y%m%d'), file_name),
                    'state': '文件写入错误'
                }
                return JsonResponse(res)

